package com.bdqn.config;

import com.bdqn.base.Global;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * RabbitMQConfig
 *
 * @author LILIBO
 * @since 2023-03-23
 */
@Configuration
public class RabbitMQConfig implements InitializingBean {

    /**
     * 自动注入RabbitTemplate模板
     */
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息JSON序列化
     */
    @Override
    public void afterPropertiesSet() {
        // 使用JSON序列化
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
    }

    /**
     * 创建一个Email交换机
     */
    @Bean
    public DirectExchange directExchangeEmail() {
        return new DirectExchange(Global.EXCHANGE_NAME_EMAIL);
    }

    /**
     * 创建一个Email队列
     */
    @Bean
    public Queue directQueueEmail() {
        return new Queue(Global.QUEUE_NAME_EMAIL);
    }

    /**
     * 将Email队列绑定到交换机，并设置路由Key为“cloud.email”
     */
    @Bean
    public Binding bindingEmail() {
        return BindingBuilder.bind(directQueueEmail()).to(directExchangeEmail()).with(Global.ROUTING_KEY_EMAIL);
    }

}
